<template>
	<view class="container">
		<!-- 省市县 -->
			<u-picker :show="cityShow" :columns="cityList" @cancel="close" keyName="name"
			@confirm="confirmCitySelect" @change="changeHandler" ref="cityPicker"></u-picker>	
	</view>
</template>

<script>
	import Api from "@/config/api.js"
	export default {
		data() {
			return {
				cityList: [],
				cityShow:true,
			}
		},
		props: {
			id: {
				type:String,
				default:() => ""
			}
		},
		mounted() {
			 this.getProvinceData()
		},
		methods: {
			close() {
				this.cityShow = false
			},
			show() {
				this.cityShow = true
			},
			
			/**
				 * 省市区变化
				 */
				changeHandler(e) {
					// console.log(e );
					let { columnIndex,
                    value,
                    values, // values为当前变化列的数组内容
                    index} = e 
					let list = values[columnIndex]
					if ( columnIndex == 0 ) {
						this.$refs['cityPicker'].setColumnValues(1, list[index].children)
						this.$refs['cityPicker'].setColumnValues(2, list[index].children[0].children)
						this.cityList[1] = list[index].children
						this.cityList[2] = list[index].children[0].children
					} else if (columnIndex == 1 ) {
						this.$refs['cityPicker'].setColumnValues(2, list[index].children)
						this.cityList[2] = list[index].children
					}
					// console.log( this.cityList );
					
					
				},
				/**
				 * 获取省市县
				 */
				async getProvinceData() {
					// console.log("获取地区");																										
					let id = parseInt( this.id )
					this.cityList = []
					let areaStr = uni.getStorageSync("area")
					if ( areaStr ) {
						this.cityList.push(JSON.parse(areaStr))
					} else {
						let res = await Api.getCity({ id })
						// console.log( res );
						if ( res.code == 1 ) {
							let list  = res.data 
							uni.setStorageSync("area", JSON.stringify( list ))
							this.cityList.push( res.data )
							
						} else if ( res.code == 0 ) {
							setTimeout(() => {
								console.log("back");
								uni.navigateBack()
							},1500)
						}
					}
					
					if ( this.cityList.length && this.cityList[0].length ) {
						let item = this.cityList[0][0]
						if ( item  && item.children ) {
							this.cityList.push(item.children)
							let el = item.children[0]
							if ( el && el.children) {
								this.cityList.push(el.children)
							}
						}
					}
					
				},
			
			/**
			 * @param {Object} 确定选择省市县
			 */
			confirmCitySelect(e) {
				this.$emit("select",e.value)
				this.close()
			},
			
		},
	}
</script>

<style lang="scss" scoped>
</style>